<?php


namespace app\common\controller;


use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Session;

class Common extends Controller
{



	//获取config配置
    public function selconfig(){
        return null;
    }


    /**
     * 权限控制查询
     * @author zhixuedong
     * @date 2021/1/19/019
     */
    public function currentId(){
        $request= Request::instance();
        $module=strtolower($request->module());
        $controller=strtolower($request->controller());
        $action=strtolower($request->action());

        $where['module_name'] = $module;
        $where['controller_name'] = $controller;
        $where['action_name'] = $action;
        $role_id = Db::name("privilege")->where($where)->value("id");
        return $role_id;
    }



    //生成日志
    public function createlog($data){
        $data['addtime'] = time();
        $data['operator_id'] = Session::get("id");
        Db::name("admin_fans_log")->insert($data);
    }


    /**
     * 查询配置选项
     * @param $key
     * @return array|mixed
     * @author zhixuedong
     * @date 2021/1/20/020
     */
    public function publicAttribute($key){
        //服务类型
        $data = Db::name("config_attribute")->where(['key'=>$key])->value("value");
        $data = explode("|",$data);
        foreach ($data as $k=>$v){
            $data[$k+1] = $v;
        }
        unset($data[0]);
        return $data;
    }

    /**
     * 权限查询
     * @param int $role_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhixuedong
     * @date 2021/1/20/020
     */
    public function showpower($role_id=0){
        if(empty($role_id)){
            $role_id = $this->power();
        }
        //获取下级栏目
        $publicTable = "privilege";
        $publicWhere['parent_id'] = $role_id;
        $publicWhere['status'] = 1;
        $field = "id,name,module_name,controller_name,action_name";
        $newSql = $this->public_select($publicTable,$publicWhere,$field);
        $privilege = $newSql->order("sort desc")->select();
        //列表查询
        $powerList = $this->powerList($privilege);
        if(count($powerList)==0){
            $this->error("暂无权限");
        }
       return $powerList;
    }


    /**
     * 查询条件
     * @author zhixuedong
     * @date 2021/1/20/020
     */
    public function public_select($table,$where,$field=null,$start=0,$limit=0){
        $data = Db::name($table)->where($where);
        if($limit!=0){
            $data = $data->limit($start,$limit);
        }
        if(!empty($field)){
            $data = $data->field($field);
        }
        return $data;
    }

    public function handle($table,$data,$type=0){
        if(empty($data['id'])){
            if(empty($type)){
                $data['addtime'] = time();
                $data['add_id'] = Session::get("id");
            }
            $id = Db::name($table)->insertGetId($data,true);
        }else{
            $id = $data['id'];
            if(empty($type)){
                $data['updatetime'] = time();
                $data['update_id'] = Session::get("id");
            }
            Db::name($table)->where(['id'=>$id])->update($data);
        }
        return $id;
    }


    /**
     * 权限列表
     * @author zhixuedong
     * @date 2021/1/20/020
     */
    public function powerList($privilege){
        $role = Session::get("role");

        if($role!=1){
            $where1['id'] = $role;
            $privilege_list = Db::name("role")->where($where1)->value("privilege_list");
            $privilege_list = explode(",",$privilege_list);
            foreach ($privilege as $k=>$v){
                $power = in_array($v['id'],$privilege_list);
                if(!$power){
                    unset($privilege[$k]);
                }
            }
        }
        foreach ($privilege as $k=>$v){
            $privilege[$k]['url'] = "/".$v["module_name"]."/".$v['controller_name']."/".$v['action_name'];
        }
        return $privilege;
    }


    /**
     * 权限控制查询
     * @author zhixuedong
     * @date 2021/1/19/019
     */
    public function power(){
        $request= Request::instance();
        $module=strtolower($request->module());
        $controller=strtolower($request->controller());
        $action=strtolower($request->action());
        $role = Session::get("role");

        $where['module_name'] = $module;
        $where['controller_name'] = $controller;
        $where['action_name'] = $action;
        $role_id = Db::name("privilege")->where($where)->value("id");
        if($role!=1){
            $where1['id'] = $role;
            $privilege_list = Db::name("role")->where($where1)->value("privilege_list");
            $privilege_list = explode(",",$privilege_list);
            $power = in_array($role_id,$privilege_list);
            if(!$power){
                $this->error("暂无权限");
            }
        }

        if($role_id!=0){
            $role_id = Db::name("privilege")->where($where)->value("parent_id");
        }

        return $role_id;
    }


    //获取小区分布信息
    public function Distribute(){
        try{
            $superior_code = $_POST['superior_code'];


            if($superior_code==100000){
                $where['level'] = 1;
            }else{
                if($superior_code==110000){
                    $superior_code = 110100;
                }
                if($superior_code==120000){
                    $superior_code = 120100;
                }
                if($superior_code==500000){
                    $superior_code = 500100;
                }
                if($superior_code==310000){
                    $superior_code = 310100;
                }
                $where['superior_code'] = $superior_code;
            }


            //获取所有省份
            $list = Db::name("admin_region")
                ->field("name,level,code,id,superior_code")
                ->where($where)->select();

            $newValue = [];
            foreach ($list as $k=>$v){
                switch ($v['level']){
                    case 1:
                        $where1['provinceId'] = $v['id'];
                        break;
                    case 2:
                        $where1['fcityId'] = $v['id'];
                        break;
                    case 3:
                        $where1['cityRegionId'] = $v['id'];
                        break;
                    case 4:
                        $detail = Db::name("admin_region")
                            ->field("name,level,code,id,superior_code")
                            ->where(['code'=>$superior_code])->field("name,level,code,id,superior_code")->find();
                        $where1['cityRegionId'] = $detail['id'];
                        $count = Db::name("admin_community")->where($where1)->count("*");
                        $newValue[$k]['name'] = $detail['name'];
                        $newValue[$k]['level'] = $detail['level'];
                        $newValue[$k]['value'] = $count;
                        $newValue[$k]['cityCode'] = intval($detail['code']);
                        $black['code'] = 0;
                        $black['data'] = $newValue;
                        return $black;
                        break;
                }
                $count = Db::name("admin_community")->where($where1)->count("*");
                $newValue[$k]['level'] = $v['level'];;
                $newValue[$k]['name'] = $v['name'];
                $newValue[$k]['value'] = $count;
                $newValue[$k]['cityCode'] = intval($v['code']);
            }
            $black['code'] = 0;
            $black['data'] = $newValue;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    function subUTF8str($str,$start=0,$length=80){
        $cur_len = 0; //人理解的字符串长度
        $all_len = strlen($str); //机器理解字符串长度
        if($length > $all_len)
        {
            return $str;
        }
        for($i = 0;$i < $all_len;)
        {
            if($cur_len == $start)
            {
                break;
            }
            if (ord($str[$i]) > 127)
            {
                $i += 3;
            }else{
                $i += 1;
            }
            $cur_len ++;
        }
        $start_pos = $i;
        $temp_pos = $cur_len;
        for(;$cur_len - $temp_pos < $length;)
        {
            if($i >= $all_len)
                break;
            if (ord($str[$i]) > 127)
            {
                $i += 3;
            }else{
                $i += 1;
            }
            $cur_len ++;
        }
        $end_pos = $i;
        return substr($str,$start_pos,$end_pos);
    }

    //商品销量统计
    public function spellStatistics(){
        $thisWechat = Session::get("thisWechat");
        $uniacid = $thisWechat['id'];
        $where['b.uniacid'] = $uniacid;

        if(!empty($_POST['id'])){
            $where['b.stores_id'] = $_POST['id'];
        }

        try{
            //统计所有商品
            $list = Db::name("admin_order_product")->alias("a")
                ->join("admin_spell b","a.product_id = b.id")
                ->where($where)
                ->field("sum(count) as newcount,b.title")
                ->group("a.product_id")
                ->order("newcount desc")
                ->select();

            $xData = [];
            $yData = [];
            foreach ($list as $item){
                $xData[] = $this->subUTF8str($item['title'],0,8);;
                $yData[] = $item['newcount'];
            }
            $black['xData'] = $xData;
            $black['yData'] = $yData;
            $black['code'] = $yData;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;

    }


    //报修单统计
    public function repairStatistics(){
        try{
            $thisWechat = Session::get("thisWechat");
            $uniacid = $thisWechat['id'];
            //物业报修统计
            $where['c.uniacid'] = $uniacid;
            if(!empty($_POST['id'])){
                $where['c.id'] = $_POST['id'];
            }
            //服务类型
            $service_type = Db::name("config_attribute")->where(['key'=>"service_type"])->value("value");
            $service_type = explode("|",$service_type);
            foreach ($service_type as $k=>$v){
                $service_type[$k+1] = $v;
            }
            unset($service_type[0]);

            $xAxis = [];
            $series = [];
            foreach ($service_type as $k=>$v){
                $count = 0;
                $where['a.type'] = $k;
                $count = Db::name("admin_repair")->alias("a")
                    ->join("admin_community_housing b","a.housing_id = b.id")
                    ->join("admin_community c","b.community_id = c.id")
                    ->where($where)->count("*");
                $xAxis[] = $v;
                $series[] = $count;
            }
            $black['code'] = 0;
            $black['xAxis'] = $xAxis;
            $black['series'] = $series;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    //更新排序
    public function updateSort(){
        try{
            Db::name($_POST['table'])->where(['id'=>$_POST['id']])->update(['sort'=>$_POST['value']]);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //获取公众号平台列表
    public function configList(){
        $uniacid = Session::get("uniacid");
        $configWhere = [];
        if(!empty($uniacid)) {
            $configWhere['id'] = $uniacid;
        }
        //获取公众号列表
        $wechatVal = Db::name("config")->where($configWhere)->select();
        return $wechatVal;
    }

    //赋值省份列表
    public function region()
    {
        $province = Db::name("admin_region")->field("id,name as title,code,superior_code")->where(['level' => ['elt', 3]])->select();
        $data = [];
        foreach ($province as $k => $v) {
            if ($v['superior_code'] == '000000') {
                $data[] = $v;
                unset($province[$k]);
            }
        }
        $ids = [];
        if (!empty($_POST['id'])) {
            $city = Db::name("admin_agent_city")->where(['agent_id' => $_POST['id']])->field("province,city,area")->select();
            $ids = [];
            foreach ($city as $k => $v) {
                foreach ($v as $v1) {
                    $ids[] = $v1;
                }
            }
            $ids = array_unique($ids);
        }
        foreach ($data as $k => $v) {
//            if(in_array($v['id'],$ids)){
//                $data[$k]['checked'] = true;
//            }
            foreach ($province as $k1 => $v1) {
//                if(in_array($v1['id'],$ids)){
//                    $province[$k1]['checked'] = true;
//                }
                if ($v['code'] == $v1['superior_code']) {
                    foreach ($province as $k2 => $v2) {
                        if (in_array($v2['id'], $ids)) {
                            $v2['checked'] = true;
                        }
                        if ($v1['code'] == $v2['superior_code']) {
                            $v1['children'][] = $v2;
                        }
                    }
                    $data[$k]['children'][] = $v1;
                }
            }
        }
        //获取城市信息
        /*$province = Db::name("admin_region")->field("id,name as title,code")->where(['superior_code'=>'000000'])->select();
        foreach ($province as $k=>$v){
            $val = Db::name("admin_region")->field("id,name as title,code")->where(['superior_code'=>$v['code']])->select();
            foreach ($val as $k1=>$v1){
                $val1 = Db::name("admin_region")->field("id,name as title,code")->where(['superior_code'=>$v1['code']])->select();
                $val[$k1]['children'] = $val1;
            }
            $province[$k]['children'] = $val;
        }*/
        $black['data'] = $data;
        return $black;
    }


    //切换平台
    public function sclickWitch(){
        try{

            $id = $_POST['id'];
            $wechat = Db::name("config")->where(['status'=>1,'id'=>$id])->find();
            $wechat['avatar'] = empty($wechat['avatar'])?"/static/images/nopic-107.png":$wechat['avatar'];
            Session::set("thisWechat",$wechat);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //权限条件生成
    public function storeWhere($auto){
        switch ($auto){
            case 1:
                //查询所代理的区域
                $cityWhere['agent_id'] = Session::get("id");
                $agent_city = Db::name("admin_agent_city")->where($cityWhere)->field("area")->select();
                $agent_city = array_column($agent_city,"area");
                $agent_city = empty($agent_city)?-1:$agent_city;
                $where['area_id'] = ['in',$agent_city];
                break;
            case 4:
                $store_id = Db::name("admin_stores_manage")->where(['id'=>Session::get("id")])->value("store_id");
                $where['id'] = $store_id;
            default:
                $where = [];
                break;
        }
        return $where;
    }

    //查询省市区id
    public function findregionId($name){
        $id = Db::name("admin_region")->where(['name'=>$name])->value("id");
        return $id;
    }

    //解析地址
    public function handleAddress($address)
    {
        preg_match('/(.*?(省|自治区|北京市|天津市))/', $address, $matches);
        if (count($matches) > 1) {
            $province = $matches[count($matches) - 2];
            $address = str_replace($province, '', $address);
        }
        preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
        if (count($matches) > 1) {
            $city = $matches[count($matches) - 2];
            $address = str_replace($city, '', $address);
        }
        preg_match('/(.*?(市|区|县|镇|乡|街道))/', $address, $matches);
        if (count($matches) > 1) {
            $area = $matches[count($matches) - 2];
            $address = str_replace($area, '', $address);
        }
        return [
            'province' => isset($province) ? $province : '',
            'city' => isset($city) ? $city : '',
            'area' => isset($area) ? $area : '',
        ];
    }

    //充值视图
    public function topupView()
    {
        //获取粉丝信息
        $detail = Db::name("admin_fans")->where(['id'=>$_POST['id']])->field("id,nickname,realName,mobile,avatar,balance,integral")->find();
        $this->assign("detail",$detail);
        return view("topupView");
    }

    //积分操作视图
    public function integralView()
    {
        if(empty($_POST['table'])){
            //志愿者信息
            $detail = Db::name("community_registration")->where(['id'=>$_POST['id']])->field("id,name,mobile,integral")->find();
            $type = 1;
        }else{
            //党员信息
            $detail = Db::name("community_record")->where(['id'=>$_POST['id']])->field("id,name,integral")->find();
            $detail['mobile'] = '';
            $type = 2;
        }
        $this->assign("type",$type);
        $this->assign("detail",$detail);
        return view("integralView");
    }


    //根据小区获取分类
    public function findClassify(){
        $id = $_POST['id'];
        $where['community_id'] = $id;
        //查询楼栋信息
        $classify = Db::name("admin_news_classify")->where($where)->field("id,name")->select();
        $black['code'] = 0;
        $black['data'] = $classify;
        return $black;
    }


    public function newAuto($communityWhere){
        //获取小区
        $auto = Session::get("auto");
        if(!empty($auto)){
            switch ($auto){
                case "1":
                    //查询所代理的区域
                    $cityWhere['agent_id'] = Session::get("id");
                    $agent_city = Db::name("admin_agent_city")->whereOr($cityWhere)->field("area")->select();
                    $agent_city = array_column($agent_city,"area");
                    $agent_city = empty($agent_city)?-1:$agent_city;
                    $communityWhere['cityRegionId']= ['in',$agent_city];
                    break;
                case "2":
                    //查询所管理的小区
                    $cityWhere['manager_id'] = Session::get("id");
                    $community_id = Db::name("admin_manager_community")->whereOr($cityWhere)->field("community_id")->select();
                    $community_id = array_column($community_id, "community_id");
                    $community_id = empty($community_id)?-1:$community_id;
                    $communityWhere['id']= ['in',$community_id];
                    break;
                default:
            }
        }
        return $communityWhere;
    }


    //下发人员信息到设备
    public function addPerson(){
        try{

            $sex = Db::name("config_attribute")->where(['key'=>"sex"])->value("value");
            $sex = explode("|",$sex);
            foreach ($sex as $k=>$v){
                $sex[$k+1] = $v;
            }
            unset($sex[0]);

            //获取设备信息
            $device = Db::name("admin_device")->where(['id'=>$_POST['id']])->field("community_id,sn")->find();
            $where['d.id'] = $device['community_id'];
            $where['b.faceUrl'] = ['neq',''];
            $where['a.status'] = 1;
            //查询小区业主信息
            $list = Db::name("admin_owner")->alias("a")->join("admin_fans b","a.fans_id = b.id")
                ->join("admin_community_housing c","a.housing_id = c.id")
                ->join("admin_community d","c.community_id = d.id")
                ->join("admin_community_element e","c.element_id = e.id")
                ->join("admin_community_building f","c.building_id = f.id")
                ->field("a.id personId,b.realName name,b.sex,b.idCard idNo,b.mobile phone,a.cardNumber icCard,b.faceUrl faceImg,a.effectiveStartTime effectTime,a.effectiveEndTime validTime")
                ->order("a.id desc")->where($where)->select();

            foreach ($list as $k=>$v){
                $list[$k]['sex'] = $sex[$v['sex']];
                $list[$k]['validTime'] = -1;
                $list[$k]['timeInterval'] = '';
                $imgToBase64 = $this->imgToBase64(ROOT_PATH."public".$v['faceImg']);
                $list[$k]['faceImg'] = $imgToBase64;
            }

            $data['messageId'] = $this->getRandom(32);
            $data['command'] = 'addPerson';
            $data['sn'] = $device['sn'];
            $data['data']['personList'] = $list;
            $black['code'] = 0;
            $black['msg'] = "操作成功";
            $black['data'] = $data;
        }catch (Exception $e){
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    function imgToBase64test($img_file) {

        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等

            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限

            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }

                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码

            }
            fclose($fp);
        }

        return $img_base64; //返回图片的base64
    }


    //图片转换Base64
    function imgToBase64($file) {

        if($fp = fopen($file,"rb", 0))
        {
            $gambar = fread($fp,filesize($file));
            fclose($fp);

            $base64 = base64_encode($gambar);
            $base64 = str_replace(array('+','/','='),array('-','_',''),$base64);
            return $base64;
            // 输出
            //$encode = '<img src="data:image/jpg/png/gif;base64,' . $base64 .'" >';
            //return $base64;


            /*$data = str_replace(array('-','_'),array('+','/'),$string);
            $mod4 = strlen($data) % 4;
            if ($mod4) {
                $data .= substr('====', $mod4);
            }
            return base64_decode($data);*/

        }
    }


    //验证手机格式
    public function isMobile($mobile) {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
    }

    //验证身份证
    public static function setCard($card)
    {
        $city = [11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江 ", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北 ", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏 ", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外 "];
        $tip = "";
        $match = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/";
        $pass = true;
        if (!$card || !preg_match($match, $card)) {
            //身份证格式错误
            $pass = false;
        } else if (!$city[substr($card, 0, 2)]) {
            //地址错误
            $pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (strlen($card) == 18) {
                $card = str_split($card);
                //∑(ai×Wi)(mod 11)
                //加权因子
                $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                $parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                $sum = 0;
                $ai = 0;
                $wi = 0;
                for ($i = 0; $i < 17; $i++) {
                    $ai = $card[$i];
                    $wi = $factor[$i];
                    $sum += $ai * $wi;
                }
                $last = $parity[$sum % 11];
                if ($parity[$sum % 11] != $card[17]) {
//                        $tip = "校验位错误";
                    $pass = false;
                }
            } else {
                $pass = false;
            }
        }
        if (!$pass) return false;/* 身份证格式错误*/
        return true;/* 身份证格式正确*/
    }


    function getRandom($param)
    {
        $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $key = "";
        for ($i = 0; $i < $param; $i++) {
            $key .= $str{mt_rand(0, 32)};    //生成php随机数
        }
        return $key;
    }


    //根据身份证获取年龄
    function getAgeByID($id)
    {
        if (empty($id)) return '';
        $date = strtotime(substr($id, 6, 8));
        $today = strtotime('today');
        $diff = floor(($today - $date) / 86400 / 365);
        $age = strtotime(substr($id, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;
        return $age;
    }


    //获取微信公众号配置信息
    public function config()
    {
        $config = Db::name("config")->find();
        return $config;
    }

    //模板通知功能
    public function visitors()
    {
        try {
            $WeChat = new WeChat();
            $config = $this->config();
            $id = $_POST['id'];
            //查询当前访客信息
            $owner = Db::name("admin_visitors")->where(['id' => $id])->find();
            //获取房源信息
            $housing = Db::name("admin_community_housing")->where(['id' => $owner['housing_id']])->field("community_id,building_id,element_id")->find();
            //查询小区名称
            $propertyName = Db::name("admin_community")->where(['id' => $housing['community_id']])->value("propertyName");
            //查询楼栋
            $buildingName = Db::name("admin_community_building")->where(['id' => $housing['building_id']])->value("buildingName");
            //查询单元
            $elementName = Db::name("admin_community_element")->where(['id' => $housing['element_id']])->value("elementName");
            //获取接收人openid
            $fans = Db::name("admin_fans")->where(['id' => $owner['fans_id']])->field("openid,realName,mobile")->find();
            $time = date("Y-m-d H:i:s"); //当前时间
            $type = empty($_POST['type']) ? 1 : $_POST['type'];
            if ($type == 2) {
                //刷卡进门提醒
                $data['first']['value'] = "尊敬的访客，您好！";
                $data['keyword1']['value'] = "暂无卡号"; //卡号
                $data['keyword2']['value'] = $propertyName . "北门设备"; //刷卡设备：
                $data['keyword3']['value'] = $time; //进门时间：
                $data['remark']['value'] = "您已开门成功，感谢您的使用！";
                $post_data['touser'] = $fans['openid'];
                $post_data['template_id'] = "y5tN0KKCveTetnHN-lPMDb0mxDcOxtGd6RfNOQ0ZUkI"; //模板ID
                $post_data['appid'] = $config['appid'];
                $post_data['data'] = $data;
                $post_data['url'] = "https://live.zicmg.com/addons/we7_wmall/template/vue/index.html?menu=#/pages/home/index?i=1";
                $WeChat->template_send($post_data);
                //记录来访日志
                $log['remark'] = "用户【" . $fans['realName'] . "】已通过" . $propertyName . "北门设备";
                $log['controller'] = "Common";
                $log['methods'] = "visitors";
                $this->adduserLog($log);
            } else {
                //通知家人来访通知
                $family = Db::name("admin_owner")->where(['housing_id' => $owner['housing_id']])->field("fans_id")->select();
                /*foreach ($family as $k=>$v){
                    if($v['fans_id']==$owner['fans_id']){
                        unset($family[$k]);
                    }
                }*/
                $family = array_column($family, "fans_id");
                $family_openid = Db::name("admin_fans")->where(['id' => ['in', $family]])->field("openid")->select();
                $family_openid = array_column($family_openid, "openid");
                //获取物业电话
                $hotline = Db::name("admin_community")->where(['id' => $housing['community_id']])->value("hotline");
                $data['first']['value'] = "您有一位访客即将到来";
                $data['keyword1']['value'] = $fans['realName']; //卡号
                $data['keyword2']['value'] = $fans['mobile']; //刷卡设备：
                $data['keyword3']['value'] = $time; //进门时间：
                $data['remark']['value'] = "门卫已放行，如有疑问，可联系放行门卫值班电话" . $hotline;
                $post_data1['template_id'] = "PF3MmpATsxJzIRiOBz9jUBPr_Ei8XkILMKP-OB17zto"; //模板ID
                $post_data1['appid'] = $config['appid'];
                $post_data1['data'] = $data;
                foreach ($family_openid as $k => $v) {
                    $post_data1['touser'] = $v;
                    $WeChat->template_send($post_data1);
                }
            }
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    //模板通知功能
    public function visiting()
    {
        try {
            $WeChat = new WeChat();
            $config = $this->config();
            $id = $_POST['id'];
            //查询当前业主信息
            $owner = Db::name("admin_owner")->where(['id' => $id])->find();
            //获取房源信息
            $housing = Db::name("admin_community_housing")->where(['id' => $owner['housing_id']])->field("community_id,building_id,element_id")->find();
            //查询小区名称
            $propertyName = Db::name("admin_community")->where(['id' => $housing['community_id']])->value("propertyName");
            //查询楼栋
            $buildingName = Db::name("admin_community_building")->where(['id' => $housing['building_id']])->value("buildingName");
            //查询单元
            $elementName = Db::name("admin_community_element")->where(['id' => $housing['element_id']])->value("elementName");
            //获取接收人openid
            $fans = Db::name("admin_fans")->where(['id' => $owner['fans_id']])->field("openid,realName,mobile")->find();
            $time = date("Y-m-d H:i:s"); //当前时间
            $type = empty($_POST['type']) ? 1 : $_POST['type'];
            if ($type == 2) {
                //刷卡进门提醒
                $data['first']['value'] = "尊敬的业主，您好！";
                $data['keyword1']['value'] = $owner['cardNumber']; //卡号
                $data['keyword2']['value'] = $propertyName . "北门设备"; //刷卡设备：
                $data['keyword3']['value'] = $time; //进门时间：
                $data['remark']['value'] = "您已开门成功，感谢您的使用！";
                $post_data['touser'] = $fans['openid'];
                $post_data['template_id'] = "y5tN0KKCveTetnHN-lPMDb0mxDcOxtGd6RfNOQ0ZUkI"; //模板ID
                $post_data['appid'] = $config['appid'];
                $post_data['data'] = $data;
                $post_data['url'] = "https://live.zicmg.com/addons/we7_wmall/template/vue/index.html?menu=#/pages/home/index?i=1";
                $WeChat->template_send($post_data);
                //记录来访日志
                $log['remark'] = "用户【" . $fans['realName'] . "】已通过" . $propertyName . "北门设备";
                $log['controller'] = "Common";
                $log['methods'] = "visiting";
                $this->adduserLog($log);
            } else {
                //通知家人来访通知
                $family = Db::name("admin_owner")->where(['housing_id' => $owner['housing_id']])->field("fans_id")->select();
                /*foreach ($family as $k=>$v){
                    if($v['fans_id']==$owner['fans_id']){
                        unset($family[$k]);
                    }
                }*/
                $family = array_column($family, "fans_id");
                $family_openid = Db::name("admin_fans")->where(['id' => ['in', $family]])->field("openid")->select();
                $family_openid = array_column($family_openid, "openid");
                //获取物业电话
                $hotline = Db::name("admin_community")->where(['id' => $housing['community_id']])->value("hotline");
                $data['first']['value'] = "您有一位访客即将到来";
                $data['keyword1']['value'] = $fans['realName']; //卡号
                $data['keyword2']['value'] = $fans['mobile']; //刷卡设备：
                $data['keyword3']['value'] = $time; //进门时间：
                $data['remark']['value'] = "门卫已放行，如有疑问，可联系放行门卫值班电话" . $hotline;
                $post_data1['template_id'] = "PF3MmpATsxJzIRiOBz9jUBPr_Ei8XkILMKP-OB17zto"; //模板ID
                $post_data1['appid'] = $config['appid'];
                $post_data1['data'] = $data;
                foreach ($family_openid as $k => $v) {
                    $post_data1['touser'] = $v;
                    $WeChat->template_send($post_data1);
                }
            }
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    //开启摄像头视图
    public function faceView()
    {
        return view("faceView");
    }

    //获取粉丝基本信息
    public function fansDetail()
    {
        try {
            $where['id'] = $_POST['id'];
            $data = Db::name("admin_fans")->field("id,realName,idCard,mobile,faceUrl")->where($where)->find();
            $black['code'] = 0;
            $black['data'] = $data;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['data'] = "暂无基本信息";
        }
        return $black;
    }

    //删除业主
    public function delOwner()
    {
        try {
            $id = $_POST['id'];
            $detail = Db::name("admin_owner")->where(['id' => $id])->find();
            //获取业主名称
            $realName = Db::name("admin_fans")->where(['id' => $detail['fans_id']])->value("realName");
            $housing = Db::name("admin_community_housing")->where(['id' => $detail['housing_id']])->field("community_id,building_id,element_id,roomNumber")->find();
            //查询小区名称
            $propertyName = Db::name("admin_community")->where(['id' => $housing['community_id']])->value("propertyName");
            //查询楼栋
            $buildingName = Db::name("admin_community_building")->where(['id' => $housing['building_id']])->value("buildingName");
            //查询单元
            $elementName = Db::name("admin_community_element")->where(['id' => $housing['element_id']])->value("elementName");
            $log['remark'] = "用户【" . Session::get("user_name") . "】删除小区【" . $propertyName . "】,楼栋【" . $buildingName . "】,单元【" . $elementName . "】房源【" . $housing['roomNumber'] . "】的房源业主,业主名称【" . $realName . "】业主id【" . $detail['fans_id'] . "】";
            Db::name("admin_owner")->where(['id' => $id])->delete();
            $log['controller'] = "Common";
            $log['methods'] = "delOwner";
            $this->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //车辆列表
    public function cartView(){
        $this->assign("id", $_POST['id']);
        return view("cartView");
    }

    //获取车辆列表
    public function cartList()
    {
        $page = empty($_GET['page']) ? 1 : $_GET['page'];
        $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
        $start = ($page - 1) * $limit;

        //获取房源id
        $owner = Db::name("admin_owner")->where(['id'=>$_GET['id']])->find();

        $where = "1=1 and housing_id = " . $owner['housing_id'];
        if (!empty($_GET['keyword'])) {
            $keyword = $_GET['keyword'];
            $where .= " and (name like '%" . $keyword . "%' or car_number like '%" . $keyword . "%' or mobile like '%" . $keyword . "%')";
        }

        $data = Db::name("admin_options")->where($where)
            ->field("id,car_number,name,mobile,car_floor")
            ->limit($start, $limit)->select();
        //$sex = Config::get("sex");


        //获取楼层
        $floor = Db::name("config_attribute")->where(['key'=>"floor"])->value("value");
        $floor = explode("|",$floor);
        foreach ($floor as $k=>$v){
            $floor[$k+1] = $v;
        }
        unset($floor[0]);
        $this->assign("floor",$floor);


        foreach ($data as $k=>$v){
            $data[$k]['car_floor'] = $floor[$v['car_floor']];
        }


        $count = Db::name("admin_options")->where($where)->count("*");
        $black['code'] = 0;
        $black['count'] = $count;
        $black['data'] = $data;
        return $black;
    }

    //删除车源信息
    public function delCart()
    {
        try {
            $id = $_POST['id'];
            $detail = Db::name("admin_options")->where(['id' => $id])->find();
            Db::name("admin_options")->where(['id' => $id])->delete();

            $housing = Db::name("admin_community_housing")->where(['id'=>$detail['housing_id']])->field("community_id,building_id,element_id,roomNumber")->find();
            //查询小区名称
            $propertyName = Db::name("admin_community")->where(['id'=>$housing['community_id']])->value("propertyName");
            //查询楼栋
            $buildingName = Db::name("admin_community_building")->where(['id'=>$housing['building_id']])->value("buildingName");
            //查询单元
            $elementName = Db::name("admin_community_element")->where(['id'=>$housing['element_id']])->value("elementName");
            $log['remark'] = "用户【" . Session::get("user_name") . "】删除小区【".$propertyName."】,楼栋【".$buildingName."】,单元【".$elementName."】房源【".$housing['roomNumber']."】的车源信息,车牌号【".$detail['car_number']."】,车源id【".$detail['id']."】";
            $log['controller'] = "Common";
            $log['methods'] = "delCart";
            $this->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //银行卡列表
    public function cardView(){
        $this->assign("id", $_POST['id']);
        return view("cardView");
    }

    //获取银行卡列表
    public function cardList()
    {
        $page = empty($_GET['page']) ? 1 : $_GET['page'];
        $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
        $start = ($page - 1) * $limit;
        $where = "1=1 and fans_id = " . $_GET['id'];
        if (!empty($_GET['keyword'])) {
            $keyword = $_GET['keyword'];
            $where .= " and (cardholder like '%" . $keyword . "%' or card_number like '%" . $keyword . "%')";
        }
        $data = Db::name("admin_fans_card")->where($where)
            ->field("id,bank,full_name,card_number,cardholder,idCard")
            ->limit($start, $limit)->select();
        //$sex = Config::get("sex");

        $count = Db::name("admin_fans_card")->where($where)->count("*");
        $black['code'] = 0;
        $black['count'] = $count;
        $black['data'] = $data;
        return $black;
    }

    //银行卡解绑
    public function delCard()
    {
        try {
            $id = $_POST['id'];
            $detail = Db::name("admin_fans_card")->where(['id' => $id])->find();
            Db::name("admin_fans_card")->where(['id' => $id])->delete();
            $log['remark'] = "用户【". Session::get("user_name")."】解绑粉丝id【".$detail['fans_id']."】的银行卡号【".$detail['card_number']."】";
            $log['controller'] = "Common";
            $log['methods'] = "delCard";
            $this->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    //业主管理
    public function ownerView()
    {
        $this->assign("id", $_POST['id']);
        return view("ownerView");
    }

    //获取业主列表
    public function ownerList()
    {
        $page = empty($_GET['page']) ? 1 : $_GET['page'];
        $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
        $start = ($page - 1) * $limit;
        $where = "1=1 and a.housing_id = " . $_GET['id'];
        if (!empty($_GET['keyword'])) {
            $keyword = $_GET['keyword'];
            $where .= " and (b.realName like '%" . $keyword . "%' or b.mobile like '%" . $keyword . "%')";
        }
        $data = Db::name("admin_owner")->alias("a")
            ->join("admin_fans b", "a.fans_id = b.id")
            ->where($where)
            ->field("a.id,b.faceUrl,b.realName,b.idCard,b.sex,b.mobile")
            ->limit($start, $limit)->select();
        //$sex = Config::get("sex");
        $sex = Db::name("config_attribute")->where(['key' => "sex"])->value("value");
        $sex = explode("|", $sex);
        foreach ($sex as $k => $v) {
            $sex[$k + 1] = $v;
        }
        unset($sex[0]);
        foreach ($data as $k => $v) {
            if(!empty($v['faceUrl'])){
                $data[$k]['faceUrl'] = "<img src='" . $v['faceUrl'] . "' width='65px' height='65px' >";
            }

            $data[$k]['sex'] = $sex[$v['sex']];
            $data[$k]['mobile'] = substr($v['mobile'], 0, 3) . '****' . substr($v['mobile'], 7, strlen($v['mobile']));;
        }
        $count = Db::name("admin_owner")->alias("a")
            ->join("admin_fans b", "a.fans_id = b.id")
            ->where($where)
            ->field("a.id,b.faceUrl,b.realName,b.idCard,b.sex,b.mobile")
            ->count("*");;
        $black['code'] = 0;
        $black['count'] = $count;
        $black['data'] = $data;
        return $black;
    }

    //删除所管理的社区
    public function delColony(){
        try {
            $type = empty($_POST['type']) ? "colony" : $_POST['type'];
            switch ($type) {
                case "colony":
                    $where['manager_id'] = $_POST['id'];
                    $where['colony_id'] = $_POST['colony_id'];
                    Db::name("community_colony_manager_colony")->where($where)->delete();
                    //获取社区名称
                    $propertyName = Db::name("community_colony")->where(['id' => $_POST['colony_id']])->value("name");
                    //查询管理员账号
                    $manager = Db::name("community_colony_manager")->where(['id' => $_POST['id']])->value("name");
                    $log['remark'] = "【" . Session::get("user_name") . "】删除社区管理员【" . $manager . "】所关联的社区【" . $propertyName . "】";
                    break;
                default:
                    break;
            }
            $log['controller'] = "Common";
            $log['methods'] = "delColony";
            $this->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //所管理社区
    public function colonyView(){
        $type = empty($_POST['type']) ? "colony" : $_POST['type'];
        $this->assign("type", $type);
        $this->assign("id", $_POST['id']);
        return view("colonyView");
    }

    //获取小区列表
    public function colonyLists()
    {
        $page = empty($_GET['page']) ? 1 : $_GET['page'];
        $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
        $start = ($page - 1) * $limit;
        $where = [];
        if (!empty($_GET['id'])) {
            $id = $_GET['id'];
            $type = empty($_GET['type']) ? "colony" : $_GET['type'];
            switch ($type) {
                case "colony":
                    //筛选社区
                    $colony = Db::name("community_colony_manager_colony")->field("colony_id")->where(['manager_id' => $id])->select();
                    break;
                default:
                    break;
            }
            $colony = array_column($colony, "colony_id");
            $where['id'] = ['in', $colony];
        }
        if (!empty($_GET['keyword'])) {
            $where['name'] = ['like', "%" . $_GET['keyword'] . "%"];
        }
        //查询所代理的小区
        $data = Db::name("community_colony")->field("id,name,province,fcity,cityRegion,street")->limit($start, $limit)->where($where)->select();
        foreach ($data as $k => $v) {
            $data[$k]['city'] = $v['province'] . $v['fcity'] . $v['cityRegion'];
        }
        $count = Db::name("community_colony")->where($where)->count("id");
        $black['code'] = 0;
        $black['count'] = $count;
        $black['data'] = $data;
        return $black;
    }



    //所管理小区
    public function communityManager()
    {
        $type = empty($_POST['type']) ? "manager" : $_POST['type'];
        $this->assign("type", $type);
        $this->assign("id", $_POST['id']);
        return view("communityManager");
    }

    //删除所管理小区
    public function delCommunity()
    {
        try {
            $type = empty($_POST['type']) ? "manager" : $_POST['type'];
            switch ($type) {
                case "manager":
                    $where['manager_id'] = $_POST['id'];
                    $where['community_id'] = $_POST['community_id'];
                    Db::name("admin_manager_community")->where($where)->delete();
                    //获取小区名称
                    $propertyName = Db::name("admin_community")->where(['id' => $_POST['community_id']])->value("propertyName");
                    //查询管理员账号
                    $manager = Db::name("admin_manager")->where(['id' => $_POST['id']])->value("name");
                    $log['remark'] = "【" . Session::get("user_name") . "】删除管理员【" . $manager . "】所管理的小区权限，删除所管理的小区名称【" . $propertyName . "】";
                    break;
                case "gridmember":
                    $where['gridmember_id'] = $_POST['id'];
                    $where['community_id'] = $_POST['community_id'];
                    Db::name("admin_gridmember_community")->where($where)->delete();
                    //获取小区名称
                    $propertyName = Db::name("admin_community")->where(['id' => $_POST['community_id']])->value("propertyName");
                    //查询管理员账号
                    $manager = Db::name("admin_gridmember")->where(['id' => $_POST['id']])->value("name");
                    $log['remark'] = "【" . Session::get("user_name") . "】删除网格员【" . $manager . "】所绑定的小区【" . $propertyName . "】";
                    break;
                case "colony":
                    $where['colony_id'] = $_POST['id'];
                    $where['community_id'] = $_POST['community_id'];
                    Db::name("community_colony_community")->where($where)->delete();
                    //获取小区名称
                    $propertyName = Db::name("admin_community")->where(['id' => $_POST['community_id']])->value("propertyName");
                    //查询管理员账号
                    $manager = Db::name("community_colony")->where(['id' => $_POST['id']])->value("name");
                    $log['remark'] = "【" . Session::get("user_name") . "】删除社区【" . $manager . "】所关联的小区【" . $propertyName . "】";
                    break;
                default:
                    break;
            }
            $log['controller'] = "Common";
            $log['methods'] = "delCommunity";
            $this->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    //获取管理员账号信息
    public function managerDetail()
    {
        $type = empty($_POST['type']) ? 'manager' : $_POST['type'];
        $where['fans_id'] = $_POST['id'];
        switch ($type) {
            case "manager":
                $detail = Db::name("admin_manager")->where($where)->find();
                break;
            case "gridmember":
                $detail = Db::name("admin_gridmember")->where($where)->find();
                break;
            case "district":
                $detail = Db::name("community_colony_manager")->where($where)->find();
                break;
            default:
                break;
        }
        if (empty($detail)) {
            $black['code'] = 1;
            $black['data'] = "未绑定账号";
        } else {
            $black['code'] = 0;
            $black['data'] = $detail;
        }
        return $black;
    }


    //获取小区列表
    public function communityLists()
    {
        $page = empty($_GET['page']) ? 1 : $_GET['page'];
        $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
        $start = ($page - 1) * $limit;
        $where = [];
        if (!empty($_GET['id'])) {
            $id = $_GET['id'];
            $type = empty($_GET['type']) ? "manager" : $_GET['type'];
            switch ($type) {
                case "manager":
                    //筛选小区
                    $community = Db::name("admin_manager_community")->field("community_id")->where(['manager_id' => $id])->select();
                    break;
                case "gridmember":
                    //筛选小区
                    $community = Db::name("admin_gridmember_community")->field("community_id")->where(['gridmember_id' => $id])->select();
                    break;
                case "colony":
                    //筛选小区
                    $community = Db::name("community_colony_community")->field("community_id")->where(['colony_id' => $id])->select();
                    break;
                default:
                    break;
            }
            $community = array_column($community, "community_id");
            $where['id'] = ['in', $community];
        }
        if (!empty($_GET['keyword'])) {
            $where['propertyName'] = ['like', "%" . $_GET['keyword'] . "%"];
        }
        $auto = Session::get("auto");
        if (!empty($auto)) {
            switch ($auto) {
                case "1":
                    //查询所代理的区域
                    $cityWhere['agent_id'] = Session::get("id");
                    $agent_city = Db::name("admin_agent_city")->whereOr($cityWhere)->field("area")->select();
                    $agent_city = array_column($agent_city, "area");
                    $agent_city = empty($agent_city) ? -1 : $agent_city;
                    $where['cityRegionId'] = ['in', $agent_city];
                    break;
                case "2":
                    //查询所管理的小区
                    $cityWhere['manager_id'] = Session::get("id");
                    $community_id = Db::name("admin_manager_community")->whereOr($cityWhere)->field("community_id")->select();
                    $community_id = array_column($community_id, "community_id");
                    $community_id = empty($community_id) ? -1 : $community_id;
                    $where['id'] = ['in', $community_id];
                    break;
                case "3":
                    //查询所管理的小区
                    $cityWhere['gridmember_id'] = Session::get("id");
                    $community_id = Db::name("admin_gridmember_community")->whereOr($cityWhere)->field("community_id")->select();
                    $community_id = array_column($community_id, "community_id");
                    $community_id = implode($community_id, ",");
                    $community_id = empty($community_id) ? -1 : $community_id;
                    $where['id'] = ['in', $community_id];
                    break;
                default:
            }
        }

        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];

        //查询所代理的小区
        $data = Db::name("admin_community")->field("id,propertyName,propertyNo,province,fcity,cityRegion,street")->limit($start, $limit)->where($where)->select();
        foreach ($data as $k => $v) {
            $data[$k]['city'] = $v['province'] . $v['fcity'] . $v['cityRegion'];
        }
        $count = Db::name("admin_community")->field("id,propertyName")->where($where)->count("id");
        $black['code'] = 0;
        $black['count'] = $count;
        $black['data'] = $data;
        return $black;
    }


    //选择小区视图
    public function communityList()
    {
        if (empty($_POST['type'])) {
            if (empty($_POST['keyword'])) {
                $black['code'] = 0;
                $black['data'] = [];
                $black['msg'] = "暂无数据";
            } else {
                $where = [];
                $keyword = $_POST['keyword'];
                if (!empty($keyword)) {
                    $where['propertyName'] = ['like', "%" . $keyword . "%"];
                }
                $auto = Session::get("auto");
                if (!empty($auto)) {
                    //查询所代理的区域
                    $cityWhere['agent_id'] = Session::get("id");
                    $agent_city = Db::name("admin_agent_city")->whereOr($cityWhere)->field("area")->select();
                    $agent_city = array_column($agent_city, "area");
                    $where['cityRegionId'] = ['in', $agent_city];
                }


                $thisWechat = Session::get("thisWechat");
                $where['uniacid'] = $thisWechat['id'];

                //查询所代理的小区
                $data = Db::name("admin_community")->field("id,propertyName")->where($where)->select();
                $black['code'] = 0;
                $black['data'] = $data;
            }
            return $black;
        } else {
            return view("communitylist");
        }
    }


    //用户选择框视图
    public function userList()
    {
        if (empty($_POST['type'])) {
            if (empty($_POST['keyword'])) {
                $black['code'] = 0;
                $black['data'] = [];
                $black['msg'] = "暂无数据";
            } else {
                //$sex = Config::get("sex");
                $sex = Db::name("config_attribute")->where(['key' => "sex"])->value("value");
                $sex = explode("|", $sex);
                foreach ($sex as $k => $v) {
                    $sex[$k + 1] = $v;
                }
                unset($sex[0]);
                $keyword = $_POST['keyword'];
//                $where['nickname'] = ['like', "%" . $keyword . "%"];
//                $where['id'] = intval($keyword);
//                $where['mobile'] = ['like', "%" . $keyword . "%"];
//                $where['realName'] = ['like', "%" . $keyword . "%"];
                if(is_numeric($keyword)){
                    $where = "(nickname like '%".$keyword."%' or id like '%".intval($keyword)."%' or mobile like '%".$keyword."%' or realName like '%".$keyword."%')";
                }else{
                    $where = "(nickname like '%".$keyword."%' or realName like '%".$keyword."%')";
                }




                $thisWechat = Session::get("thisWechat");
                $where .= " and uniacid = ".$thisWechat['id'];


                $data = Db::name("admin_fans")->whereOr($where)->field("id,nickname,avatar,mobile,sex,realName,idCard,faceUrl")->select();
                foreach ($data as $k => $v) {
                    $data[$k]['sex'] = $sex[$v['sex']];
                    $data[$k]['faceUrl'] = empty($v['faceUrl']) ? "/static/images/nopic-107.png" : $v['faceUrl'];
                    $data[$k]['idCard'] = substr_replace($v['idCard'], str_repeat('*', 6), 6, 8);
                    $data[$k]['mobile'] = substr($v['mobile'], 0, 3) . '****' . substr($v['mobile'], 7, strlen($v['mobile']));;
                }
                $black['code'] = 0;
                $black['data'] = $data;
            }
            return $black;
        } else {
            return view("userList");
        }
    }


    //询问弹框
    public function bounced()
    {
        $title = empty($_POST['title']) ? "提示" : $_POST['title'];
        $msg = empty($_POST['msg']) ? "" : $_POST['msg'];
        $id = empty($_POST['id']) ? 0 : $_POST['id'];
        $operation = empty($_POST['operation']) ? "confirm" : $_POST['operation'];
        $this->assign([
            "title" => $title,
            "msg" => $msg,
            "id" => $id,
            "operation" => $operation
        ]);
        //取消原因
        if ($operation == "cancel") {
            $Cancel_reason = Config::get("Cancel_reason");
//            $Cancel_reason = Db::name("config_attribute")->where(['key' => "Cancel_reason"])->value("value");
//            $Cancel_reason = explode("|", $Cancel_reason);
//            foreach ($Cancel_reason as $k => $v) {
//                $Cancel_reason[$k + 1] = $v;
//            }
//            unset($Cancel_reason[0]);
            $this->assign('Cancel_reason', $Cancel_reason);
        }
        return view("bounced");
    }

    //记录日志
    public function addLog($data)
    {
        $request= Request::instance();
        $data['controller'] = $request->controller();
        $data['methods'] = $request->action();
        $thisWechat = Session::get("thisWechat");
        $data['uniacid'] = $thisWechat['id'];
        $data['operator'] = empty($data['operator'])?Session::get("user_name"):$data['operator'];
        $data['operator_id'] = empty($data['operator_id'])?Session::get("id"):$data['operator_id'];
        $data['addtime'] = time();
        $data['ip'] = request()->ip();
        Db::name("admin_log")->insert($data);
    }

    //记录日志
    public function adduserLog($data)
    {
        $data['operator'] = Session::get("user_name");
        $data['operator_id'] = Session::get("id");
        $data['addtime'] = time();
        $data['ip'] = request()->ip();
        Db::name("admin_user_log")->insert($data);
    }

    //验证手机号
    public function is_mobile($text)
    {
        $search = '/^0?1[3|4|5|6|7|8][0-9]\d{8}$/';
        if (preg_match($search, $text)) {
            return (true);
        } else {
            return (false);
        }
    }

    //记录添加账号信息
    public function addAccountData($data)
    {
        Db::name("admin_account_data")->insert($data);
    }

    //记录添加账号信息(修改)
    public function updateAccountData($data, $table, $id)
    {
        Db::name("admin_account_data")->where(['table' => $table, 'table_id' => $id])->update($data);
    }


    //地图座标选择
    public function map()
    {
        $lng = empty($_POST['lng']) ? '' : $_POST['lng'];
        $lat = empty($_POST['lat']) ? '' : $_POST['lat'];
        $address = empty($_POST['address']) ? '' : $_POST['address'];
        $this->assign([
            "lng" => $lng,
            "lat" => $lat,
            "address"=>$address
        ]);
        return view("map");
    }


    //获取小区列表
    public function communityApi($cityRegionId,$colony)
    {
        $where['cityRegionId'] = $cityRegionId;

        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];

        $list = Db::name("admin_community")->field("id,propertyName")->where($where)->select();
        foreach ($list as $k => $v) {
            if(!empty($colony)){
                $where1['colony_id'] = ['neq',$colony];
            }
            $where1['community_id'] = $v['id'];
            $detail = Db::name("community_colony_community")->where($where1)->value("*");
            $list[$k]["check"] = empty($detail) ? 0 : 1;
            if(!empty($colony)){
                $where2['colony_id'] = $colony;
                $where2['community_id'] = $v['id'];
                $check = Db::name("community_colony_community")->where($where2)->value("*");
            }
            $list[$k]["select"] = empty($check) ? 0 : 1;
        }
        return $list;
    }

    //下拉联动
    public function cityApi()
    {
        $level = empty($_POST['level']) ? 2 : $_POST['level'];
        $id = $_POST['id'];
        //获取代理商代理的区域
        $auto = Session::get("auto");
        //信息
        $where['level'] = $level;
        if (!empty($auto)) {
            $agent_id = Session::get("id");
            $value = "";
            switch ($level) {
                case 2:
                    $where1['agent_id'] = $agent_id;
                    $where1['province'] = $id;
                    $value = Db::name("admin_agent_city")->where($where1)->field("province,city,area")->select();
                    $value = array_column($value, "city");
                    $value = array_unique($value);
                    $where['id'] = ['in', $value];
                    break;
                case 3:
                    $where1['agent_id'] = $agent_id;
                    $where1['city'] = $id;
                    $value = Db::name("admin_agent_city")->where($where1)->field("province,city,area")->select();
                    $value = array_column($value, "area");
                    $value = array_unique($value);
                    $where['id'] = ['in', $value];
                    break;
                case 4:
                    $code = Db::name("admin_region")->where(['id' => $id])->value('code');
                    $where['superior_code'] = $code;
                    break;
                default:
                    $value = array_column($value, "province");
                    $value = array_unique($value);
                    $where['id'] = ['in', $value];
            }
        } else {
            $code = Db::name("admin_region")->where(['id' => $id])->value('code');
            $where['superior_code'] = $code;
        }
        $region = Db::name("admin_region")->field("id,name,code")->where($where)->select();

        $black['code'] = 0;
        $black['data'] = $region;
        return $black;
    }


    //获取标签
    public function getTag(){
        $id = $_POST['id'];
        $tag = Db::name("admin_article_tag")->where(['colony_id'=>$id,'status'=>1])->field("id,name")->select();
        $black['code'] = 0;
        $black['data'] = $tag;
        return $black;
    }

    //获取楼栋地址信息
    public function getRegion()
    {
        $id = $_POST['id'];
        $where['id'] = $id;
        $data = Db::name("admin_community")->where($where)->field("province,fcity,cityRegion")->find();
        //查询楼栋信息
        $building = Db::name("admin_community_building")->where(['community_id' => $id])->field("id,buildingName")->select();
        $black['code'] = 0;
        $black['data'] = $data['province'] . $data['fcity'] . $data['cityRegion'];
        $black['building'] = $building;
        return $black;
    }

    //获取单元信息
    public function getElement()
    {
        $id = $_POST['id'];
        $where['building_id'] = $id;
        //查询单元信息
        $element = Db::name("admin_community_element")->where($where)->field("id,elementName,floor,roomLayout")->select();
        $black['code'] = 0;
        $black['data'] = $element;
        return $black;
    }

    //获取单元的楼层数&户数
    public function getFloor()
    {
        $id = $_POST['id'];
        $where['id'] = $id;
        //查询单元信息
        $data = Db::name("admin_community_element")->where($where)->field("floor,roomLayout")->find();
        $floor = [];
        for ($i = 1; $i <= $data['floor']; $i++) {
            $floor[] = sprintf("%02d", $i);
        }
        $room = [];
        for ($j = 1; $j <= $data['roomLayout']; $j++) {
            $room[] = sprintf("%02d", $j);
        }
        $black['code'] = 0;
        $black['floor'] = $floor;
        $black['room'] = $room;
        return $black;
    }


}